package com.oss.base.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.oss.base.BaseConst;
import com.sun.tools.javac.code.Attribute.Array;

public class PolicyBuilder {
	Map<String,List<String>> param=new HashMap<String,List<String>>();
	
	
	public PolicyBuilder setParam(String name,String value){
		
		List<String> paramVal = param.get(name)==null?new ArrayList<String>():param.get(name);
		
		paramVal.add(value);
		param.put(name, paramVal);
		
		return this;
	}
	
	
	public String build(){
		StringBuffer res = new StringBuffer();
		//组装头部
		res.append("{\"Version\": \"1\",");
		res.append("\"Statement\":[{");
		
		//组装action
		res.append("\"Action\":[");
		int i = 0;
		
		for(String val:param.get(BaseConst.POLICY_COND_ACTION)){
			i++;
			
			res.append(BaseConst.POLICY_COND_ACTION_PREFIX+val+BaseConst.POLICY_COND_POSTFIX);
			
			if(i < param.get(BaseConst.POLICY_COND_ACTION).size()){
				res.append(",");
			}
			
		}
		
		//组装resource
		res.append("],");
		res.append("\"Resource\":[");
		i = 0;
		
		for(String val:param.get(BaseConst.POLICY_COND_RESOURCE)){
			i++;
			
			res.append(BaseConst.POLICY_COND_RESOURCE_PREFIX+param.get(BaseConst.POLICY_COND_BUCKET).get(0)+"/"+val+"*"+BaseConst.POLICY_COND_POSTFIX);
			
			if(i < param.get(BaseConst.POLICY_COND_RESOURCE).size()){
				res.append(",");
			}
			
		}
		res.append("],");
		res.append("\"Effect\":\"Allow\"}");
		res.append("]}");
		
		return res.toString();
		
	}


	public PolicyBuilder setParam(String name, String[] values) {
		List<String> paramVal = param.get(name)==null?new ArrayList<String>():param.get(name);
		
		paramVal.addAll(Arrays.asList(values));
		param.put(name, paramVal);
		
		return this;
	}

}
